import 'package:flutter/material.dart';
import 'package:fluttermodule/config/iconfont.dart';
import 'package:fluttermodule/customerDetail/customer_detail.dart';
import 'package:fluttermodule/provide/clients.dart';

import 'package:provide/provide.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class CustomerList extends StatefulWidget {
  // CustomerList({Key key}) : super(key: key);

  @override
  _CustomerListState createState() => _CustomerListState();
}

class _CustomerListState extends State<CustomerList> {
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    return Scaffold(
        appBar: AppBar(
          title: Text("全部顾客"),
          centerTitle: true,
        ),
        body: FutureBuilder(
            future: _getInfo(context),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                var result = Provide.value<ClientsProvide>(context).clientsModel;
                return Container(
                    color: Color(0xfff5f5f5),
                    child: Column(children: <Widget>[
                      Search(),
                      Operation(),
                      Expanded(child: ScrollList(result:result))
                    ]));
              } else {
                return Text("");
              }
            }));
  }

  Future _getInfo(BuildContext context) async {
    try {
      await Provide.value<ClientsProvide>(context).getClients();
    } catch (e) {
      print(e);
    }
    return "完成加载";
  }
}

class Search extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: ScreenUtil().setSp(16)),
      decoration: BoxDecoration(color: Colors.white, boxShadow: [
        BoxShadow(
            offset: Offset(0, 0), color: Color.fromRGBO(178, 178, 178, 0.25))
      ]),
      child: TextField(
        maxLines: 1, //最大行数
        autocorrect: true, //是否自动更正
        style: TextStyle(
            fontSize: ScreenUtil().setSp(32), color: Colors.black), //输入文本的样式
        decoration: InputDecoration(
            prefixIcon: Icon(IconFont.icon_search),
            border: OutlineInputBorder(borderSide: BorderSide.none),
            hintText: '搜索',
            hintStyle: TextStyle(
                fontSize: ScreenUtil().setSp(32), color: Color(0xff999999))),
        onChanged: (text) {
          //内容改变的回调
          print('change $text');
        },
        onSubmitted: (text) {
          //内容提交(按回车)的回调
          print('submit $text');
        },
        enabled: true, //是否禁用
      ),
    );
  }
}

class Operation extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(72),
      padding: EdgeInsets.only(
        left: ScreenUtil().setSp(30),
        right: ScreenUtil().setSp(28),
      ),
      color: Colors.white,
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(children: <Widget>[
              Text(
                '默认排序',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: ScreenUtil().setSp(30),
                ),
              ),
              SizedBox(width: ScreenUtil().setWidth(10)),
              Icon(IconFont.icon_arrow_down)
            ]),
            Row(children: <Widget>[
              Text(
                '筛选',
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: ScreenUtil().setSp(30),
                ),
              ),
              SizedBox(
                width: ScreenUtil().setWidth(8),
              ),
              Icon(
                IconFont.icon_filtrate,
                color: Color(0xff666666),
              )
            ]),
          ]),
    );
  }
}

class ScrollList extends StatefulWidget {
  var result;
  ScrollList({Key key,this.result}):super(key:key);
  @override
  _ScrollListState createState() => _ScrollListState();
}

class _ScrollListState extends State<ScrollList> {
  List<String> letters = [];
  List<dynamic> data;

  ScrollController _scrollController = ScrollController();
  int _currentIndex = 0;
  final _titleHeight = ScreenUtil().setHeight(48);
  final _itemHeight = ScreenUtil().setHeight(100);


  @override
  void initState() {
    super.initState();
    this.scrollListener();
    var result = widget.result;
    if (result.code == 0) {
      this.setState(() {
        data = List<dynamic>.from(result.data);
        data.sort((a, b) {
          List<int> al = a.name.codeUnits;
          List<int> bl = b.name.codeUnits;
          for (int i = 0; i < al.length; i++) {
            if (bl.length <= i) return 1;
            if (al[i] > bl[i]) {
              return 1;
            } else if (al[i] < bl[i]) {
              return -1;
            }
          }
          return 0;
        });
        for (int i = 0; i < data.length; i++) {
          letters.add(data[i].name.toUpperCase());
        }
      });
    }
  }

  void scrollListener() {
    _scrollController.addListener(() {
      var _offsetHeight = _scrollController.offset;
      for (int i = 0; i < data.length; i++) {
        double _totalHeight = (i + 1) * _titleHeight;
        for (int j = 0; j < i; j++) {
          _totalHeight += data[j].listData.length * _itemHeight;
        }
        double _currentHeight = _totalHeight;
        double _nextHeight =
            _totalHeight + data[i].listData.length * _itemHeight;
        if (_offsetHeight >= _currentHeight && _offsetHeight < _nextHeight) {
          setState(() {
            _currentIndex = i;
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {


    return Padding(
        padding: EdgeInsets.only(
          left: ScreenUtil().setSp(30),
          right: ScreenUtil().setSp(12),
        ),
        child: Stack(children: <Widget>[
          Container(
            child: ListView.builder(
                controller: _scrollController,
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        height: _titleHeight,
                        color: Color.fromRGBO(245, 245, 245, 1),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '${data[index].name}',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(24),
                            height: 1,
                            color: Color.fromRGBO(102, 102, 102, 1),
                          ),
                        ),
                      ),
                      ListView.builder(
                        itemBuilder: (BuildContext context, int index2) {
                          return Container(
                            height: _itemHeight,
                            child: GestureDetector(
                              child: Container(
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: ScreenUtil().setSp(72),
                                      height: ScreenUtil().setSp(72),
                                      decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        image: DecorationImage(
                                          image: NetworkImage(
                                            '${data[index].listData[index2].avatar}',
                                          ),
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      width: ScreenUtil().setWidth(20),
                                    ),
                                    Expanded(
                                      child: Container(
                                        height: double.infinity,
                                        alignment: Alignment.centerLeft,
                                        decoration: UnderlineTabIndicator(
                                          borderSide: BorderSide(
                                            width: 1.0,
                                            color: Color(0xfff5f5f5),
                                          ),
                                        ),
                                        child: Text(
                                          "${data[index].listData[index2].name}",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(32),
                                            color: Color(0xff000000),
                                            height: 1,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                Navigator.push(context, MaterialPageRoute(
                                  builder: (context) {
                                    return CustomerDetailPage(
                                        code: data[index].listData[index2].code,
                                        name:
                                            data[index].listData[index2].name);
                                  },
                                ));
                              },
                            ),
                          );
                        },
                        itemCount: data[index].listData.length,
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                      ) //禁用滑动事件),
                    ],
                  );
                }),
          ),
          Align(
            alignment: new FractionalOffset(1.0, 0.5),
            child: SizedBox(
              width: ScreenUtil().setWidth(20),
              child: Padding(
                padding: EdgeInsets.only(top: ScreenUtil().setSp(30)),
                child: ListView.builder(
                  itemCount: letters.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GestureDetector(
                      child: Container(
                        margin: EdgeInsets.only(bottom: ScreenUtil().setSp(10)),
                        child: Text(
                          letters[index],
                          style: TextStyle(
                              color: Color(0xff666666),
                              fontSize: ScreenUtil().setSp(18),
                              fontWeight: index == _currentIndex
                                  ? FontWeight.bold
                                  : FontWeight.normal),
                        ),
                      ),
                      onTap: () {
                        setState(() {
                          _currentIndex = index;
                        });
                        var height = index * _titleHeight;
                        for (int i = 0; i < index; i++) {
                          height += data[i].listData.length * _itemHeight;
                        }
                        _scrollController.jumpTo(height);
                      },
                    );
                  },
                ),
              ),
            ),
          )
        ]));
  }
}
